<?php

/**
 * Access control management
 *
 * @version 1.0
 * @package CMS/Controller/Plugin
 */
class CMS_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
{

    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        if (!Zend_Auth::getInstance()->hasIdentity())
        {
            $credential = ($request->getParam('credential')) ?
                    $request->getParam('credential') :
                    $this->getRequest()->getCookie('credential');
            if ($credential)
            {
                $adapter = new CMS_Auth_Adapter(NULL, NULL, NULL, NULL, $credential);
                try
                {
                    $result = Zend_Auth::getInstance()->authenticate($adapter);
                    if ($request->getParam('remember'))
                        setcookie('credential', $request->getParam('credential'), time() + 604800, '/', $_SERVER['HTTP_HOST']);
                }
                catch (CMS_Auth_Exception $e)
                {
                    setcookie('credential', '', time() - 1296000, '/', $_SERVER['HTTP_HOST']);
                }
            }
        }

        $acl = CMS_Acl::getInstance();

        try
        {
            if (!$acl->hasPermission($request->getControllerName(), $request->getActionName()))
                $this->forbiddenRoute($request);
        }
        catch (Zend_Acl_Exception $e)
        {
            $this->notFoundRoute($request);
        }
    }

    /**
     * Checks wheter the current user is logged in or not,
     * and changes the route to a proper controller/action
     *
     * @param string $role
     * @param Zend_Controller_Request_Abstract $request
     */
    private function forbiddenRoute(Zend_Controller_Request_Abstract $request)
    {
        $request->setControllerName('forbidden');
        $request->setActionName('index');
    }

    /**
     * Checks wheter the current user is logged in or not,
     * and changes the route to a proper controller/action
     *
     * @param string $role
     * @param Zend_Controller_Request_Abstract $request
     */
    private function notFoundRoute(Zend_Controller_Request_Abstract $request)
    {
        $request->setControllerName('notfound');
        $request->setActionName('pagenotfound');
    }

}